package com.louzhu.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.louzhu.common.to.es.SkuEsModel;
import com.louzhu.common.utils.R;
import com.louzhu.gulimall.search.GulimallSearchApplication;
import com.louzhu.gulimall.search.config.GulmallElasticsearchConfig;
import com.louzhu.gulimall.search.constant.EsConstant;
import com.louzhu.gulimall.search.feign.ProductFeignService;
import com.louzhu.gulimall.search.service.MallSearchService;
import com.louzhu.gulimall.search.vo.AttrResponseVo;
import com.louzhu.gulimall.search.vo.SearchParam;
import com.louzhu.gulimall.search.vo.SearchResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.lucene.search.TotalHits;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MallSearchServiceImpl implements MallSearchService {

    @Autowired
    private RestHighLevelClient client;
    @Autowired
    private ProductFeignService productFeignService;

    /**
     * 检索方法
     * @param searchParam 页面请求的检索参数
     * @return 返回给页面的数据
     */
    @Override
    public SearchResult search(SearchParam searchParam) {
        /*
        返回结果
         */
        SearchResult searchResult = null;
        /*
        构建检索请求
         */
        SearchRequest searchRequest =buildSearchRequest(searchParam);
        try {
            /*
            执行检索请求
            */
            SearchResponse searchResponse = client.search(searchRequest, GulmallElasticsearchConfig.COMMON_OPTIONS);
            /*
            分析检索结果，封装在指定的结果对象中
             */
            searchResult = buildSearchResult(searchResponse,searchParam);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return searchResult;
    }

    /**
     * 根据页面请求参数构建出ES检索请求
     * @param searchParam 检索参数
     * @return 检索请求
     */
    private SearchRequest buildSearchRequest(SearchParam searchParam) {
        /*
        DSL语句构造器
         1 模糊匹配、过滤（分类、品牌、属性、价格、库存状态过滤）
         2 排序
         3 分页
         4 高亮
         5 聚合分析
         */
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        // 1- 查询 boolQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        // boolQuery 中的 must 关键字模糊匹配
        if(!StringUtils.isEmpty(searchParam.getKeyword())){
            boolQuery.must(QueryBuilders.matchQuery("skuTitle",searchParam.getKeyword()));
        }

        // boolQuery 中的 filter 按照三级分类ID过滤
        if(null != searchParam.getCatalog3Id()){
            boolQuery.filter(QueryBuilders.termQuery("catelogId",searchParam.getCatalog3Id()));
        }

        // boolQuery 中的 filter 按照品牌ID过滤
        if(null != searchParam.getBrandId() && searchParam.getBrandId().size()>0){
            boolQuery.filter(QueryBuilders.termsQuery("brandId",searchParam.getBrandId()));
        }

        // boolQuery 中的 filter 按照有无库存过滤 页面请求传来0表示查询无库存1表示查询有库存
        boolQuery.filter(QueryBuilders.termQuery("hasStock",searchParam.getHasStock() == 1));

        // boolQuery 中的 filter 按照价格区间过滤,页面请求参数中已经按照固定的格式发送价格区间参数
        // _500 表示小于等于500；100_500 表示大于等于100小于等于500；500_ 表示大于等于500
        RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("skuPrice");
        if (!StringUtils.isEmpty(searchParam.getSkuPrice())) {
            String[] prices = searchParam.getSkuPrice().split("_");
            if (prices.length == 1) {
                if (searchParam.getSkuPrice().startsWith("_")) {
                    rangeQueryBuilder.lte(Integer.parseInt(prices[0]));
                }else {
                    rangeQueryBuilder.gte(Integer.parseInt(prices[0]));
                }
            } else if (prices.length == 2) {
                //_6000会截取成["","6000"]
                if (!prices[0].isEmpty()) {
                    rangeQueryBuilder.gte(Integer.parseInt(prices[0]));
                }
                rangeQueryBuilder.lte(Integer.parseInt(prices[1]));
            }
            boolQuery.filter(rangeQueryBuilder);
        }

        // boolQuery 中的 filter 按照 属性查询(嵌入式) attrs-nested
        // 固定的格式：attrs=1_5寸:8寸&2_16G:8G
        List<String> attrs = searchParam.getAttrs();
        BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
        if (null !=attrs &&attrs.size() > 0) {
            attrs.forEach(attr->{
                String[] attrSplit = attr.split("_");
                queryBuilder.must(QueryBuilders.termQuery("attrs.attrId", attrSplit[0]));
                String[] attrValues = attrSplit[1].split(":");
                queryBuilder.must(QueryBuilders.termsQuery("attrs.attrValue", attrValues));
            });
        }
        NestedQueryBuilder nestedQueryBuilder = QueryBuilders.nestedQuery("attrs", queryBuilder, ScoreMode.None);
        boolQuery.filter(nestedQueryBuilder);

        searchSourceBuilder.query(boolQuery);

        // 2- 排序
        // 固定格式：sort=saleCount_desc/asc
        if (!StringUtils.isEmpty(searchParam.getSort())) {
            String[] sortSplit = searchParam.getSort().split("_");
            searchSourceBuilder.sort(sortSplit[0], sortSplit[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC);
        }

        //3-分页 检测结果分页
        searchSourceBuilder.from((searchParam.getPageNum() - 1) * EsConstant.PRODUCT_PAGESIZE);
        searchSourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);

        //4- 高亮highlight 关键字模糊匹配的时候才高亮
        if (!StringUtils.isEmpty(searchParam.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            // 高亮字段
            highlightBuilder.field("skuTitle");
            // 高亮样式：前缀
            highlightBuilder.preTags("<b style='color:red'>");
            // 高亮样式：后缀
            highlightBuilder.postTags("</b>");
            searchSourceBuilder.highlighter(highlightBuilder);
        }

        // 5 聚合：品牌/分类/属性

        // 5-1 聚合品牌
        TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg").field("brandId").size(50);
        // 品牌子聚合：品牌名称聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(1));
        // 品牌子聚合：品牌图片聚合
        brand_agg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(1));
        searchSourceBuilder.aggregation(brand_agg);

        // 5-2 聚合分类
        TermsAggregationBuilder catelog_agg = AggregationBuilders.terms("catelog_agg").field("catelogId").size(20);
        // 分类子聚合
        catelog_agg.subAggregation(AggregationBuilders.terms("catelog_name_agg").field("catelogName").size(1));
        searchSourceBuilder.aggregation(catelog_agg);

        // 5-3 聚合属性
        NestedAggregationBuilder attr_agg = AggregationBuilders.nested("attr_agg", "attrs");
        // 聚合出当前所有属性ID
        TermsAggregationBuilder attr_id_agg = AggregationBuilders.terms("attr_id_agg").field("attrs.attrId");
        // 聚合每个属性ID下的属性名
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(1));
        // 聚合每个属性ID对应的属性值
        attr_id_agg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(50));
        attr_agg.subAggregation(attr_id_agg);
        searchSourceBuilder.aggregation(attr_agg);


        System.out.println("DSL语句构建完成：" + searchSourceBuilder.toString());

        /*
        根据DSL构造器、指定索引，构建出检索请求
         */
        SearchRequest searchRequest = new SearchRequest(new String[]{EsConstant.PRODUCT_INDEX}, searchSourceBuilder);
        /*
        返回构建完成的检索请求
         */
        return searchRequest;
    }

    /**
     * 根据检索响应数据构建需要的检索结果
     * @param searchResponse 检索响应数据
     * @return 符合需求格式的检索结果
     */
    private SearchResult buildSearchResult(SearchResponse searchResponse,SearchParam searchParam) {

        SearchResult searchResult = new SearchResult();

        SearchHits hits = searchResponse.getHits();
        /*
        1-从响应数据的 hits 中获取查询到的商品数据封装在返回结果中
         */
        // 商品信息
        if (hits.getHits()!=null&&hits.getHits().length>0){
            List<SkuEsModel> skuEsModels = new ArrayList<>();
            for (SearchHit hit : hits) {
                String sourceAsString = hit.getSourceAsString();
                SkuEsModel skuEsModel = JSON.parseObject(sourceAsString, SkuEsModel.class);
                //设置高亮属性
                if (!StringUtils.isEmpty(searchParam.getKeyword())) {
                    HighlightField skuTitle = hit.getHighlightFields().get("skuTitle");
                    String highLight = skuTitle.getFragments()[0].string();
                    skuEsModel.setSkuTitle(highLight);
                }
                skuEsModels.add(skuEsModel);
            }
            searchResult.setProducts(skuEsModels);
        }

        // 总记录数
        long total = hits.getTotalHits().value;
        searchResult.setTotal(total);
        // 总页码
        Integer totalPages = (int)total % EsConstant.PRODUCT_PAGESIZE == 0 ?
                (int)total / EsConstant.PRODUCT_PAGESIZE : (int)total / EsConstant.PRODUCT_PAGESIZE + 1;
        searchResult.setTotalPages(totalPages);

        // 页码集合
        List<Integer> pageNavs = new ArrayList<>();
        for (int i=1;i<=totalPages;i++){
            pageNavs.add(i);
        }
        searchResult.setPageNavs(pageNavs);
        // 当前页，从请求参数中获取
        searchResult.setPageNum(searchParam.getPageNum());


        /*
        2-从响应数据的 aggregations 中获取聚合信息
         */
        Aggregations aggregations = searchResponse.getAggregations();

        // 2.1 封装分类信息
        List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
        ParsedLongTerms catelog_agg = aggregations.get("catelog_agg");
        for (Terms.Bucket bucket : catelog_agg.getBuckets()) {
            SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
            // 获取分类id
            String keyAsString = bucket.getKeyAsString();
            catalogVo.setCatalogId(Long.parseLong(keyAsString));
            // 分类名称（分类名称只有一个）
            ParsedStringTerms catelog_name_agg = bucket.getAggregations().get("catelog_name_agg");
            String catelog_name = catelog_name_agg.getBuckets().get(0).getKeyAsString();
            catalogVo.setCatalogName(catelog_name);

            catalogVos.add(catalogVo);
        }
        searchResult.setCatalogs(catalogVos);

        // 2.2 封装品牌信息
        List<SearchResult.BrandVo> brandVos = new ArrayList<>();
        ParsedLongTerms brand_agg = aggregations.get("brand_agg");
        for (Terms.Bucket bucket : brand_agg.getBuckets()) {
            SearchResult.BrandVo brandVo = new SearchResult.BrandVo();
            // 得到品牌id
            Long brandId = bucket.getKeyAsNumber().longValue();
            brandVo.setBrandId(brandId);

            Aggregations subBrandAggs = bucket.getAggregations();
            // 得到品牌图片
            ParsedStringTerms brandImgAgg=subBrandAggs.get("brand_img_agg");
            String brandImg = brandImgAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandImg(brandImg);
            // 得到品牌名字
            ParsedStringTerms brandNameAgg=subBrandAggs.get("brand_name_agg");
            String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
            brandVo.setBrandName(brandName);

            brandVos.add(brandVo);
        }
        searchResult.setBrands(brandVos);

        // 2.3 封装属性信息
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();
        ParsedNested parsedNested=searchResponse.getAggregations().get("attr_agg"); // ParsedNested用于接收内置属性的聚合
        ParsedLongTerms attrIdAgg=parsedNested.getAggregations().get("attr_id_agg");
        for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
            SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
            // 查询属性id
            String keyAsString = bucket.getKeyAsString();
            attrVo.setAttrId(Long.parseLong(keyAsString));

            Aggregations subAttrAgg = bucket.getAggregations();

            // 查询属性名
            ParsedStringTerms attrNameAgg=subAttrAgg.get("attr_name_agg");
            String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();
            attrVo.setAttrName(attrName);

            // 查询属性值
            ParsedStringTerms attrValueAgg = subAttrAgg.get("attr_value_agg");
            List<String> attrValues = new ArrayList<>();
            for (Terms.Bucket attrValueAggBucket : attrValueAgg.getBuckets()) {
                String attrValue = attrValueAggBucket.getKeyAsString();
                attrValues.add(attrValue);
            }
            attrVo.setAttrValue(attrValues);

            attrVos.add(attrVo);
        }
        searchResult.setAttrs(attrVos);

        // 3- 封装面包屑导航数据
        List<String> attrs = searchParam.getAttrs();
        if (attrs != null && attrs.size() > 0) {
            List<SearchResult.NavVo> navVos = attrs.stream().map(attr -> {
                String[] split = attr.split("_");
                SearchResult.NavVo navVo = new SearchResult.NavVo();
                //6.1 设置属性值
                navVo.setNavValue(split[1]);
                //6.2 查询并设置属性名
                try {
                    R r = productFeignService.attrInfo(Long.parseLong(split[0]));
                    if (r.getCode() == 0) {
                        AttrResponseVo attrResponseVo = JSON.parseObject(JSON.toJSONString(r.get("attr")), new TypeReference<AttrResponseVo>() {
                        });
                        navVo.setNavName(attrResponseVo.getAttrName());
                    }
                } catch (Exception e) {
                    log.error("远程调用商品服务查询属性失败", e);
                }
                //6.3 设置面包屑跳转链接(当点击该链接时剔除点击属性)
                String queryString = searchParam.get_queryString();
                String replace = queryString.replace("&attrs=" + attr, "").replace("attrs=" + attr+"&", "").replace("attrs=" + attr, "");
                navVo.setLink("http://search.gulimall.com/search.html" + (replace.isEmpty()?"":"?"+replace));
                return navVo;
            }).collect(Collectors.toList());
            searchResult.setNavs(navVos);
        }


        return searchResult;
    }
}
